package com.iot.iotplus.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iot.iotplus.base.CommonPage;
import com.iot.iotplus.base.Result;
import com.iot.iotplus.base.ResultCode;
import com.iot.iotplus.entity.Device;
import com.iot.iotplus.entity.Product;
import com.iot.iotplus.entity.Tenant;
import com.iot.iotplus.mapper.DeviceMapper;
import com.iot.iotplus.mapper.ProductMapper;
import com.iot.iotplus.service.ProductService;
import com.iot.iotplus.utils.ResultUtil;
import com.iot.iotplus.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public Result<CommonPage<Product>> productList(Integer pageNum, Integer pageSize) {
        // 参数校验
        try{
            Optional.of(pageNum+pageSize);
        }catch (NullPointerException e){
            return new Result<>(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMessage(), null);
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Tenant tenantFromContext = (Tenant) authentication.getPrincipal();
        String id = tenantFromContext.getId();

        Page<Product> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getTenantId,id);
        wrapper.eq(Product::getDeleted,0);
        IPage<Product> productPage = productMapper.selectPage(page, wrapper);
        CommonPage<Product> commonPage = new CommonPage<>((int) productPage.getCurrent(),
                (int) productPage.getSize(),
                (int) productPage.getPages(),
                productPage.getTotal(),
                productPage.getRecords());
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), commonPage)                                                                                      ;
    }

    @Override
    public Result<Product> getProduct(Long productID) {
        //参数校验
        try{
            Optional.of(productID);
        }catch (NullPointerException e){
            return new Result<>(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMessage(), null);
        }
        Product product = productMapper.selectById(productID);
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), product);
    }

    @Transactional
    @Override
    public Result<?> addProduct(Product product) {
        try {
            Optional.of(product.getName());
            Optional.of(product.getAreaCode());
            Optional.of(product.getTenantId());
        }catch (NullPointerException e){
            return new Result<>(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMessage(), null);
        }
        Long id = SnowflakeIdGenerator.getSnowflakeId();
        String key = "product_" + String.valueOf(product.getAreaCode()) +"_"+ id;
        MD5 md5 = SecureUtil.md5();
        String md5str = md5.digestHex("123456");

        product.setId(String.valueOf(id));
        product.setProductKey(key);
        product.setUserName(key);
        product.setCreateTime(new Date());
        product.setPassWord(md5str);
        product.setUpdateTime(new Date());
        product.setDeleted(0);

        int insert = productMapper.insert(product);
        if (insert == 1){
            return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
        }
        return new Result<>(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage(),null);
    }

    @Override
    public Result<?> deleteProduct(Long productID) {
        try {
            Optional.of(productID);
        }catch (NullPointerException e){
            return new Result<>(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMessage(), null);
        }
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getProductId,productID);
        List<Device> devices = deviceMapper.selectList(wrapper);
        if (!devices.isEmpty())
            return ResultUtil.failed("无法删除关联表的产品!!!");
        if (productMapper.deleteById(productID) == 1){
            return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
        }
        return new Result<>(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage(),"删除失败！");
    }

    @Override
    public Result<?> bytIDGetProducts(String tenantId) {
        try{
            Optional.of(tenantId);
        }catch (NullPointerException e){
            return ResultUtil.failed();
        }
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getTenantId,tenantId);
        wrapper.eq(Product::getDeleted,0);
        List<Product> products = productMapper.selectList(wrapper);
        return ResultUtil.success(products);
    }


}
